package com.gistone.commis.spring;

import com.gistone.commis.entity.User;
import com.gistone.commis.mapper.UserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Component
public class CustomAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    private Logger logger = LoggerFactory.getLogger(this.getClass());


    public CustomAuthenticationSuccessHandler() {
    }

    @Autowired
    private UserMapper userMapper;

    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {

        boolean admin = false;
        HttpSession httpSession = request.getSession();
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String username = userDetails.getUsername();
        User user = userMapper.findUserByUserName(username);

        httpSession.setAttribute("currentUser", user);

//        for (GrantedAuthority auth : authentication.getAuthorities()) {
//            System.out.println(auth.getAuthority());
//            if ((Role.DBA.getRoleName()).equals(auth.getAuthority()) || (Role.ADMIN.getRoleName()).equals(auth.getAuthority())) {
//                admin = true;
//            }
//        }
        if (admin) {
            super.setDefaultTargetUrl("/admin/home");
        } else {
            super.setDefaultTargetUrl("/user/home");
        }

        super.onAuthenticationSuccess(request, response, authentication);
    }
}